const app = getApp();
const { appJson } = app.siteInfo;
const { qyWXCheckSeesion } = require('../../../../utils/ws/ws-wxwork');
const _util = require('../../util.js');
Page({
  data: {
    tab: '1',
    editable: '',
    customerInfo: '',
    page: '2',
    pagesize: '20',
    customerActions: [],
    customerStat: '', 
    chartVisible: false,
    isWXWork: app.isWXWork,
    systemInfo: wx.getSystemInfoSync(),
    floatItems: [
      {
        type: 0,
        show: true,
        iconClass: 'icon icon-fb',
        event: 'showChart',
      },
      {
        type: 0,
        show: false,
        iconClass: 'icon icon-gb',
        event: 'closeChart',
      },
    ],
    remarkCollapsed: true,
    chartData: [],
    legendData: [],
  },

  onLoad: function (options) {
    let { id } = options;
    if (app.isWXWork && !id) {
      this.getExternalCustomerInfo();
    } else {
      this.setData({
        customerID: id,
        customerInfo: (app.universal_card_globalData && app.universal_card_globalData.currentCustomer) || {},
      });
      this.getCustomerInfo({ id }).then(({ openid, unionid }) => {
        if (openid) {
          this.getSelectedTags();
          this.getCustomerActions(openid);
          this.getUserPortrait(openid);
          this.getCustomerRemark(openid);
          this.getCustomerStat();
        }
      });
    }
  },

  onShow: function () {
    wx.showLoading({
      title: '努力加载中',
    });
    let pages = getCurrentPages();
    let showTabBar = Array.isArray(pages) && pages.length === 1;  // 页面栈只有当前页面
    let tabBarColor = (appJson[0] && appJson[0].tabBar && appJson[0].tabBar.selectedColor) || '';
    this.setData({ showTabBar, tabBarColor });
    if (this.data.customerInfo.openid) {
      this.getSelectedTags();
      this.getCustomerRemark(this.data.customerInfo.openid);
    }
  },

  initChart() {
    const { chartData, legendData  } = this.data;
    const context = wx.createCanvasContext('aiPie');
    const colors = ['#D7504B', '#C6E579', '#F4E001', '#F0805A', '#26C0C0', '#C1232B', '#B5C334' ];
    const ratio = (wx.getSystemInfoSync().screenWidth) / 750;
    const halfWidth = 180 * ratio;
    const radius = 150 * ratio;
    const total = chartData.reduce((acc, cur) => acc + cur, 0);
    
    for (let i = 0; i < chartData.length; i++) {
      context.beginPath();
      let start = 0;
      if (i > 0) {
        for (let j = 0; j < i; j++) {
          start += (chartData[j] / total) * 2 * Math.PI;
        }
      }
    
      legendData[i].color = colors[i];
      context.arc(halfWidth, halfWidth, radius, start, start + (chartData[i] / total) * 2 * Math.PI, false);
      context.setLineWidth(2);
      context.lineTo(halfWidth, halfWidth);
      context.setStrokeStyle('#F5F5F5');      
      context.setFillStyle(colors[i]);
      context.fill();
      context.closePath();
      context.stroke();
    }
    context.draw();

    this.setData({
      legendData,
    });
  },

  getExternalCustomerInfo() {
    qyWXCheckSeesion({
      success: () => {
        wx.qy.getCurExternalContact({
          success: (res) => {
            const userId = res.userId; // 返回当前外部联系人userId
            // const userId = 'wmDkH9EAAAURY8j2ljWca2d8rdJ-Q5wQ';
            console.log('external_userid', userId);
            this.getExternalUserInfo(userId).then((unionid) => {
              console.log('unionid', unionid);
              this.getCustomerInfo({ external_userid: userId }).then(extInfo => {
                console.log('extInfo', extInfo);
                if (!extInfo || !extInfo.openid) {
                  this.getCustomerInfo({ unionid }).then(unionInfo => {
                    console.log('unionInfo', unionInfo);
                    if (unionInfo && unionInfo.openid) {
                      this.updateCustomerInfo(unionInfo);
                      this.getSelectedTags();
                      this.getCustomerActions(unionInfo.openid);
                      this.getUserPortrait(unionInfo.openid);
                      this.getCustomerRemark(unionInfo.openid);
                        this.getCustomerStat();
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: '未查找到该客户的访客信息',
                        success: () => {
                          this.gotoCardHome();
                        },
                      });
                    }
                  });
                } else {
                  this.getSelectedTags();
                  this.getCustomerActions(extInfo.openid);
                  this.getUserPortrait(extInfo.openid);
                  this.getCustomerRemark(extInfo.openid);
                  this.getCustomerStat();
                }
              });
            }).catch(err => console.error(err));
          },
        });
      },
      fail: (err) => {
        console.log('企业微信登录失败', err);
      },
    });
  },

  getExternalUserInfo(externalUserId) {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'card/api/get_external_user_info',
        data: {
          external_userid: externalUserId,
        },
        success: res => {
          if (res.data && res.data.errno === 0 && res.data.data) {
            const data = res.data.data;
            const externalUserInfo = data.external_contact;
            const followUsers = data.follow_user;
            console.log('externalUserInfo', externalUserInfo);
            console.log('followUsers', followUsers);
            const { userid } = wx.getStorageSync('qyUserInfo');
            let followInfo = {};
            if (userid && followUsers && followUsers.length > 0) {
              followInfo = followUsers.find(v => v.userid === userid);
            }
            console.log('followInfo', followInfo);
            this.setData({
              externalUserInfo,
              followInfo,
            }, () => {
              resolve(externalUserInfo.unionid);
            });
          } else {
            reject(res);
          }
        },
        fail: err => {
          reject(err);
        },
      });
    });
  },

  updateCustomerInfo(unionInfo = {}) {
    const data = {
      id: unionInfo.id,
      openid: unionInfo.openid,
    };
    const info = this.data.externalUserInfo;
    const followInfo = this.data.followInfo;
    data.external_userid = info.external_userid;
    if (followInfo) {
      if (followInfo.remark_mobiles && followInfo.remark_mobiles.length > 0) {
        data.phone = followInfo.remark_mobiles[0];
      }
    }
    console.log('update_recode', data);
    app.util.request({
      url: 'card/api/update_recode',
      data,
      method: 'post',
      success: res => {
        if (res.data && res.data.errno === 0) {
          this.getCustomerInfo({ id: unionInfo.id });
        }
      },
      fail: err => {
        console.log(err);
      },
    });
  },

  getCustomerInfo({ id = '', unionid = '', external_userid = '' }) {
    return new Promise(resolve => {
      if (!id && !unionid && !external_userid) {
        resolve(null);
        return;
      }
      const data = {
        id,
        unionid,
        external_userid,
      };
      if (unionid || external_userid) {
        data.m_openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid') || wx.getStorageSync('userInfo').openid;
      }
      const url = 'card/api/get_recode_detail';
      let options = {
        url,
        data,
        method: 'get',
        chachetime: 0,
      };
      const success = res => {
        console.log('get_recode_detail', res);
        res.notes && res.notes.forEach(item => {
          item.timestamp = app.util.formatTime(item.timestamp);
        });
        res.notes = (res.notes || []).reverse();
        wx.setNavigationBarTitle({
          title: res.alias || res.name || '客户信息',
        });
        this.setData({ customerInfo: res, customerOpenid: res.openid || '' }, () => {
          resolve(res);
        });
      };
      this.doRequest(options, success);
    });
  },

  getSelectedTags() {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'card/api/personalTag',
        data: {
          openid: this.data.customerInfo.m_openid,
          client_openid: this.data.customerInfo.openid,
        },
        showLoading: true,
        success: res => {
          if (res.data && res.data.errno === 0) {
            const data = res.data.data;
            this.setData({ selectedTags: data.new || (data.old && data.old.split(' ')) || [] });
            resolve(data);
          } else {
            reject(res);
          }
        },
        fail: err => {
          reject(err);
        },
      });
    });
  },


  onInfoInput(e) {
    this.setData({ [e.currentTarget.dataset.type]: e.detail.value });
  },

  editInfo(e) {
    const url = 'card/api/update_recode';
    let customerID = this.data.customerInfo.id;
    let { customerInfo } = this.data;
    let type = e.currentTarget.dataset.type;
    let typeValue = '';
    let actions = [
      { type: 'alias', name: 'alias' },
      { type: 'deal', name: 'deal' },
      { type: 'follow', name: 'follow' },
      { type: 'notes', name: 'notes' },
      { type: 'tag', name: 'tag' },
    ];

    if (type === 'notes') {
      if (!this.data[type] || !this.data[type].trim()) {
        return wx.showToast({
          title: '内容不能为空',
          icon: 'none',
        });
      } else {
        typeValue = this.data[type];
        let inputName = actions.filter(item => item.type === type)[0].name;
        this.setData({ editable: '' });
        let options = {
          url,
          data: {
            id: customerID,
            openid: this.data.customerOpenid,
            [inputName]: typeValue,
          },
          method: 'post',
          chachetime: 0,
        };
        const success = res => {
          this.getCustomerInfo({ id: customerID });
          this.setData({ [inputName]: '' });
        };
        this.doRequest(options, success);
      }
    } else {
      typeValue = parseInt(this.data[type] || this.data.customerInfo[type]);
      if (type == 'deal' || type == 'follow') {
        if (typeValue > 100 || typeValue < 0){
          return wx.showToast({
            title: '输入数值超出范围',
            icon: 'none',
          });
        } else {
          customerInfo[type] = typeValue;
          this.setData({ customerInfo, editable: '' });
    let inputName = actions.filter(item => item.type === type)[0].name;
    let options = {
      url,
      data: {
        id: customerID,
        openid: this.data.customerOpenid,
        [inputName]: typeValue,
      },
      method: 'post',
      chachetime: 0,
    };
    const success = res => {
      this.getCustomerInfo({ id: customerID });
      this.setData({ [inputName]: '' });
    };
    this.doRequest(options, success);
        }
      }
    }
  },

  doRequest(options, success, fail) {
    app.util.request({
      ...options,
      success: (res) => {
        res.data.errno === 0 && success(res.data.data);
      },
      fail: err => {
        fail && fail(err);
      },
    });
  },

  tapTab(e) {
    let tab = e.currentTarget.dataset.tab;
    this.setData({ tab });
    tab === '1' && this.getCustomerActions(this.data.customerOpenid);
  },

  getCustomerActions(openid) {
    this.getRadarList({ openid }).then(res => {
      this.setData({ customerActions: res });
    });
  },

  getUserPortrait(openid) {
    app.util.request({
      url: 'card/api/getUserPortrait',
      data: {
        openid,
      },
      showLoading: true,
      success: res => {
        if (res.data && res.data.errno === 0) {
          const userPortrait = res.data.data;
          userPortrait.gender = userPortrait.sex === 1 ? '男' : (userPortrait.sex === 2 ? '女' : '未知');
          userPortrait.phoneInfo = (!userPortrait.phone_brand && !userPortrait.phone_model) ? '' : `${userPortrait.phone_brand} ${userPortrait.phone_model}`;
          this.setData({ userPortrait });
        }
      },
    });
  },

  showChart() {
    this.setData(
      {
      chartVisible: true,
      'floatItems[0].show': false,
      // 'floatItems[1].show': true,
      },
      () => {
        this.initChart();
      },
    );
  },

  closeChart() {
    this.setData({
      chartVisible: false,
      'floatItems[0].show': true,
      // 'floatItems[1].show': false,
    });
  },

  getCustomerStat() {
    app.util.request({
      url: 'card/api/access_statistics',
      data: {
        id: this.data.customerInfo.id,
      },
      success: res => {
        if (res.data && res.data.errno === 0) {
          const { statistics = [] } = res.data.data;
          const chartData = [];
          const legendData = statistics.map(item => {
            chartData.push(parseInt(item.percent * 100,10));
            item.percent=  `${parseInt(Number(item.percent) * 100)}%`;
            return item;
          });

          this.setData({
            legendData,
            chartData,
          });
        }
      },
    });
  },

  // drawPieChart(percentage) {
  //   const ctx = wx.createCanvasContext('pie-chart');
  //   const system = wx.getSystemInfoSync();
  //   const screenWidth = system.screenWidth;
  //   const ratio = screenWidth / 750;
  //   const radius = 150 * ratio;
  //   const halfWidth = 180 * ratio;
  //   ctx.beginPath();
  //   ctx.moveTo(halfWidth, halfWidth);
  //   ctx.arc(halfWidth, halfWidth, radius, 0, percentage * 2 * Math.PI);
  //   ctx.fillStyle = '#f96b25';
  //   ctx.fill();
  //   ctx.closePath();
  //   ctx.beginPath();
  //   ctx.moveTo(halfWidth, halfWidth);
  //   ctx.arc(halfWidth, halfWidth, radius, percentage * 2 * Math.PI, 2 * Math.PI);
  //   ctx.fillStyle = '#4dd197';
  //   ctx.fill();
  //   ctx.closePath();
  //   ctx.draw();
  // },

  startEdit(e) {
    this.setData({ editable: e.currentTarget.dataset.type });
  },

  onInfoInput(e) {
    this.setData({ [e.currentTarget.dataset.type]: e.detail.value });
  },

  onPullDownRefresh() {
    this.getRadarList({
      openid: this.data.customerOpenid || '',
    }).then(res => {
      this.setData({ customerActions: res });
    });
    wx.stopPullDownRefresh();
  },

  reachBottom() {
    this.getRadarList({
      openid: this.data.customerOpenid || '',
      page: this.data.page,
    }).then(res => {
      this.setData({
        customerActions: [...this.data.customerActions, ...res],
        page: Number(this.data.page) + 1,
      });
    });
  },

  getRadarList(opts = {}) {
    let page = opts.page && String(opts.page) || '1';
    return new Promise((resolve, reject) => app.util.request({
      url: 'card/api/new_log_list', // new_log_list
      data: {
        page,
        pagesize: this.data.pagesize,
        is_module: '1',
        cn: 'click',
        from_openid: opts.openid || '',
        keyword: opts.openid || this.data.customerOpenid,
      },
      success: res => {
        let response = res.data.errno === 0 && res.data.data[0] && res.data.data[0].sub ? res.data.data[0].sub : [];
        response.forEach(item => {
          item.detail = item.detail.split('||');
        });
        resolve(response);
      },
      fail: err => {
        reject(new Error(err));
      },
    }));
  },

  gotoMsg(e) {
    let { m_openid, cardid, openid: guestOpenid } = this.data.customerInfo;
    !this.data.isWXWork && _util.requestSubscribeMessage();
    let url = '/common/component/universal-card/pages/message?openid=' + m_openid + '&to_openid=' + guestOpenid + '&scene=inner&m_id=0';
    app.util.navigateTo(url);
  },

  callCustomer(e) {
    let { tel } = e.currentTarget.dataset;
    if (tel) {
      wx.makePhoneCall({
        phoneNumber: tel,
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '暂无客户电话',
      });
    }
  },

  gotoCardHome() {
    let url = 'common/component/universal-card/card-show';
    app.util.navigateTo(url, {}, true);
  },

  openChat() {
    let externalUserId = this.data.customerInfo.external_userid;
    if (externalUserId) {
      wx.qy.openEnterpriseChat({
        externalUserIds: externalUserId,
        groupName: '',
        success: () => {
          console.log('enterprise chat opened');
        }, fail: () => {
          wx.showToast({ title: '企业微信通讯异常', icon: 'none' })
        }
      });
    } else {
      wx.qy.selectExternalContact({
        filterType: 0,
        success: (res) => {
          const userIds = res.userIds;
          wx.qy.openEnterpriseChat({
            externalUserIds: userIds.join(';'),
            groupName: '',
            success: () => {
              console.log('enterprise chat opened');
            },
            fail: () =>{
              wx.showToast({ title: '企业微信通讯异常', icon: 'none' })
            }
          });
        }, fail: () => {
          wx.showToast({title: '企业微信通讯异常',icon:'none'})
        }
      });
    }
  },

  editTags() {
    app.util.navigateTo(`common/component/universal-card/pages/customer-info/customer-tag?openid=${this.data.customerInfo.m_openid}&customerOpenid=${this.data.customerInfo.openid}`);
  },

  editRemark() {
    app.util.navigateTo(`common/component/universal-card/pages/customer-info/customer-remark?openid=${this.data.customerInfo.openid}`);
  },

  toggleRemark() {
    this.setData({ remarkCollapsed: !this.data.remarkCollapsed });
  },

  getCustomerRemark(openid) {
    app.util.request({
      url: 'card/api/getRemarkDetail',
      data: {
        m_openid: openid,
      },
      showLoading: true,
      success: res => {
        if (res.data && res.data.errno === 0) {
          this.setData({
            remark: res.data.data,
          });
        }
      },
    });
  },

});
